import eleConfig from "@/common/eleConfig";
import Vue from 'vue'

const state = {
  projectData: {
    pageConfig: {
      pageColor: '',
      pageType: '',
      pageName: '',
    },
    elements: []
  },
  // 当前正在编辑的页面uuid
  activePageUUID: '',
  activeElement: {},   // 当前设置页面
  showPageSetting: true // 是否显示页面设置
}

const actions = {}
const mutations = {
  elementsHandler: (state, elData) => {
    const {added} = elData;
    if (added) {
      state.activeElement = state.projectData.elements[state.projectData.elements.length - 1]
      state.activePageUUID = state.activeElement.id
      state.showPageSetting = false
    }
  },
  settingPage: (state) => {
    state.activeElement = {}
  },
  setActiveElement: (state, elData) => {
    state.activeElement = elData
    state.activePageUUID = elData.id
  },
  delElement(state, elData) {
    const delIndex = state.projectData.elements.findIndex(item => item.id === elData.id)
    state.projectData.elements.splice(delIndex, 1)
    if (state.projectData.elements.length === 0) {
      for (let key in state.activeElement) {
        delete state.activeElement[key]
      }
      state.activePageUUID = ''
      state.showPageSetting = true
    } else {
      const lastElement = state.projectData.elements[state.projectData.elements.length - 1]
      console.log(lastElement)
      for (let key in lastElement) {
        state.activeElement[key] = lastElement[key]
      }
      Vue.set(state,'activePageUUID',lastElement.id)
    }
  }
}

const getters = {
  elementList() {
    return state.projectData.elements
  },
  activeElement: (state) => {
    return state.activeElement
  },
  componentsLibs() {
    return eleConfig
  },
  pageConfig() {
    return state.projectData.pageConfig
  },
  showPageSetting() {
    return state.showPageSetting
  },
  activePageUUID() {
    return state.activePageUUID
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}
